package com.ddstation.summarize.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;

import com.ddstation.common.service.DataDictionaryService;
import com.ddstation.crm.menu.entity.DtInvsManageInstitutionMenuEntity;
import com.ddstation.crm.menu.service.MenuService;
import com.ddstation.exam.entity.DtHealthManageInstitutionGroupEntity;
import com.ddstation.exchange.service.DtHealthManageInstitutionGroupService;
import com.ddstation.instrument_disinfect.model.InstrumentDisinfectResModel;
import com.ddstation.master.entity.MaDataDictionaryEntity;
import com.ddstation.util.getDateUtil;
import com.ddstation.waste_delivery.model.WasteDeliveryHeadResModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddstation.common.model.InvsCheckCommonSchParModel;
import com.ddstation.common.service.InvsItemService;
import com.ddstation.common.service.ViolationMessageService;
import com.ddstation.common.util.DateUtil;
import com.ddstation.crm.login.bean.SessionLoginData;
import com.ddstation.crud.entity.MaInvsViolationMessageEntity;
import com.ddstation.sewage.service.SewageService;
import com.ddstation.summarize.model.SummarizeResModel;
import com.ddstation.summarize.service.SummarizeService;

@Controller
public class SummarizeController {
	
	/**
	 * 页面 跳转
	 * 
	 * @param
	 * 
	 * @return
	 */
	@RequestMapping(value="invs_summarize.do")
	public String summarizeInitEvent(
			@RequestParam(required=false)String townId, // 地区id
			@RequestParam(required=false)Integer today, // 0：今日  1：本周
			@RequestParam(required=false)Integer status, // 异常状态
			@RequestParam(required=false)String otherData, // 其他参数
			Model model, HttpSession session) {

		// 从session获取基础数据
		SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY);
		if (loginData == null || loginData.getDoctor() == null || loginData.getInstitution() == null) {
			return "forward:login?timeout=true"; // session 过期
		}

		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		// 获取当天
		Calendar cale = Calendar.getInstance();
		String lastday = format.format(cale.getTime());
		//取开始时间
		String firstday = getDateUtil.getFirstday(today);

		model.addAttribute("dtFrom", firstday); 	// 当月的七天前
		model.addAttribute("dtTo", lastday); 		// 当月的最后一天
		model.addAttribute("townId", townId); 		// 地区ID
		model.addAttribute("status", status); 		// 地区ID
		if (otherData != null) {//存在其他参数则分割拼接参数
			String[] dataList = otherData.split(";");
			for(String dataInfo:dataList){
				if(dataInfo != null){
					String[] keyValue = dataInfo.split(":");
					if(keyValue.length == 2){
						model.addAttribute(keyValue[0], keyValue[1]);
					}
				}
			}
		}

		// 得到当前年月
//		Calendar c = Calendar.getInstance();
//		model.addAttribute("thisYear", c.get(Calendar.YEAR));
//		model.addAttribute("thisMonth", c.get(Calendar.MONTH) + 1 >= 10 ? c.get(Calendar.MONTH) + 1 : "0" + (c.get(Calendar.MONTH) + 1));
		model.addAttribute("operateType", 4); //初期停到医废处置TAB上
		// 来源
		model.addAttribute("sourceList", invsItemService.getInvsItemList(2));
		// 处置方式
		model.addAttribute("deliveryTypeList", invsItemService.getInvsItemList(3));
		// 医废种类
		model.addAttribute("wasteTypeList", invsItemService.getInvsItemList(1));
		// 器械、场所区分
		model.addAttribute("instrumentTypeList", invsItemService.getInvsItemList(13));
		
//		// 该诊所的器械列表
//		model.addAttribute("instrumentList", instrumentDisinfectService.searchInstrumentList(_in.getInstitutionId()));
		
		// 违规类型
		List<MaInvsViolationMessageEntity> violationMessageList = violationMessageService.selectList();
		if ( violationMessageList == null || violationMessageList.size()==0 ){
			throw new RuntimeException("master表【ma_invs_violation_message】没有数据！");
		}
		model.addAttribute("violationMessageList", violationMessageList);

		//机构类目
		List<MaDataDictionaryEntity> typeFirstList = dataDictionaryService.getCodeList("institution_type_first");

		model.addAttribute("typeFirstList", typeFirstList);

		//获取二级菜单目录
		String firstMenuUrl = "invs_summarize.do";
//		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getJurisdictionMenus(), firstMenuUrl);
		List<DtInvsManageInstitutionMenuEntity> secondMenus = menuService.getSecondMenus(loginData.getWorkbenchMenus(), firstMenuUrl);
		if(secondMenus == null){
			//无访问权限【跳转地址修改】
			return "forward:login?timeout=true";
		}
		//综合查询页面特殊逻辑处理【判断是否存在所需权限】
        Map<String, Object> jurisdictionMap = new HashMap<>();
		//遍历返回一级菜单权限map
        for(DtInvsManageInstitutionMenuEntity firstMenu:loginData.getWorkbenchMenus()){
            jurisdictionMap.put(firstMenu.getUrl().replaceFirst(".do",""),true);
        }
        //遍历返回所属二级菜单权限map
        for(DtInvsManageInstitutionMenuEntity secondMenu:secondMenus){
            jurisdictionMap.put(secondMenu.getUrl().replaceFirst(".do",""),true);
        }
		model.addAttribute("jurisdictionMap", jurisdictionMap);

		return "pc/summarize/summarize";
	}
	
	/**
	 * 诊所汇总数据查询 接口
	 * 
	 * @param SewageParModel  页面输入的条件
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_summarize.do/load", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadSummarizeListEvent(
			@RequestParam (required=false)String institutionName,
			@RequestParam (required=false)String townId,
			@RequestParam (required=false)String institutionTypeFirst,
			@RequestParam String dtFrom,
			@RequestParam String dtTo,
			HttpSession session)  {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        String invsInstitutionId = loginData.getInstitution().getId();
        // 查询实施
        // 把年月转换成时间区间
//      	String[] dtRange = DateUtil.getBeginEndDate(dateYm);
      	InvsCheckCommonSchParModel p = new InvsCheckCommonSchParModel();
      	p.setDtFrom(dtFrom);
      	p.setDtTo(dtTo);
      	p.setInvsInstitutionId(invsInstitutionId);
      	p.setInstitutionName(institutionName);
		p.setTownId(townId);
		p.setInstitutionTypeFirst(institutionTypeFirst);

		List<SummarizeResModel> datalist = summarizeService.searchInstitutions(p);

		//查询全部父子机构信息
		Map<String, String> groupRelationship = getGroupRelationship();
		//定义重新组合集合
		List<SummarizeResModel> comList=new ArrayList<>();
		Map<String, SummarizeResModel> comMap = new HashMap<>();
		for(SummarizeResModel data:datalist){
			//判断是否为子机构
			String belongId = groupRelationship.get(data.getInstitutionId());
			//父ID不存在则判断自己为父ID
			if(belongId == null){
				belongId = data.getInstitutionId();
			}else{
				//存在父ID剔除名称及机构ID
				data.setInstitutionName(null);
				data.setInstitutionId(null);
			}
			//获取当前ID数据
			SummarizeResModel agoData = comMap.get(belongId);
			if(agoData == null){
				//数据不存在则添加数据
				comMap.put(belongId,data);
			}else{
				//数据存在累加数据
				Integer prescriptionIllegalCnt = agoData.getPrescriptionIllegalCnt() + data.getPrescriptionIllegalCnt();
				Integer disinfectIllegalCnt = agoData.getDisinfectIllegalCnt() + data.getDisinfectIllegalCnt();
				Integer wasteIllegalCnt = agoData.getWasteIllegalCnt() + data.getWasteIllegalCnt();
				Integer sewageIllegalCnt = agoData.getSewageIllegalCnt() + data.getSewageIllegalCnt();
				Integer remoteIllegalCnt = agoData.getRemoteIllegalCnt()+ data.getRemoteIllegalCnt();
				Integer threeIllehalCnt = agoData.getThreeDayIllegalCnt()+ data.getThreeDayIllegalCnt();
				agoData.setPrescriptionIllegalCnt(prescriptionIllegalCnt);
				agoData.setDisinfectIllegalCnt(disinfectIllegalCnt);
				agoData.setWasteIllegalCnt(wasteIllegalCnt);
				agoData.setSewageIllegalCnt(sewageIllegalCnt);
				agoData.setRemoteIllegalCnt(remoteIllegalCnt);
				agoData.setThreeDayIllegalCnt(threeIllehalCnt);
				//替换名称为父ID对应名称
				if(data.getInstitutionName() != null){
					agoData.setInstitutionName(data.getInstitutionName());
				}
				//替换机构ID为父ID对应机构ID
				if(data.getInstitutionId() != null){
					agoData.setInstitutionId(data.getInstitutionId());
				}
				//存在一个状态为异常，则替换为异常
				if(data.getPrescriptionCheckSt() != 0){
					agoData.setPrescriptionCheckSt(-1);
				}
				if(data.getDisinfectCheckSt() != 0){
					agoData.setDisinfectCheckSt(-1);
				}
				if(data.getWasteCheckSt() != 0){
					agoData.setWasteCheckSt(-1);
				}
				if(data.getSewageCheckSt() != 0){
					agoData.setSewageCheckSt(-1);
				}
				if (data.getRemoteCheckSt()!=0){
					agoData.setRemoteCheckSt(-1);
				}
				if (data.getThreeDayCheckSt()!=0){
					agoData.setThreeDayCheckSt(-1);
				}
				//保存新累加的对象
				comMap.put(belongId,agoData);
			}
		}
		//遍历添加数据
		for (Map.Entry<String, SummarizeResModel> entry : comMap.entrySet()) {
			//仅添加存在父机构数据
			if(entry.getValue() != null && entry.getValue().getInstitutionId() != null && entry.getValue().getInstitutionName() != null){
				comList.add(entry.getValue());
			}
		}
		ret.put("datalist",comList);
		ret.put("cnt","总机构数："+comList.size());
		
		ret.put("errcode", 0);
		ret.put("errMsg", "");
		return ret;
	}

	//获取整理好的父子关系对照数据
	public Map<String,String> getGroupRelationship(){
		Map<String, String> map = new HashMap<>();
		List<DtHealthManageInstitutionGroupEntity> groupList = dtHealthManageInstitutionGroupService.selectAll();
		//遍历数据将子机构ID作为key，父机构ID作为value
		for(DtHealthManageInstitutionGroupEntity group:groupList){
			map.put(group.getChildInstitutionId(),group.getParentInstitutionId());
		}
		return map;
	}
	
	/**
	 * 诊所汇总数据查询 接口
	 * 
	 * @param SewageParModel  页面输入的条件
	 * 
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="invs_summarize.do/load_one_sum", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> loadOneInstitutionSumEvent(
			@RequestParam String institutionId,
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
			HttpSession session)  {

		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("errcode", -1);
		ret.put("errMsg", "系统出错，请稍后再试！");
		
        SessionLoginData loginData = (SessionLoginData)session.getAttribute(SessionLoginData.KEY );
        String invsInstitutionId = loginData.getInstitution().getId();
        // 访问权限check(防止异常调用)
 		if ( !sewageService.checkAccessAuthority(invsInstitutionId,institutionId)){
 			ret.put("errMsg", "没有访问权限！");
 			return ret;
 		}
 		// 把年月转换成时间区间
// 		String[] dtRange = DateUtil.getBeginEndDate(dateYm);
// 		if ( dtRange == null ){
// 			ret.put("errMsg", "时间格式错误！");
// 			return ret;
// 		}
 		// 把年月转换成时间区间
      	InvsCheckCommonSchParModel p = new InvsCheckCommonSchParModel();
      	p.setDtFrom(dtFrom);
      	p.setDtTo(dtTo);
      	p.setInvsInstitutionId(invsInstitutionId);
      	//p.setInstitutionId(institutionId);

		//查询机构全部子ID
		DtHealthManageInstitutionGroupEntity entity = new DtHealthManageInstitutionGroupEntity();
		entity.setParentInstitutionId(institutionId);
		List<DtHealthManageInstitutionGroupEntity> dtHealthManageInstitutionGroupList = dtHealthManageInstitutionGroupService.select(entity);
		//设置机构ID集合，必定存在父机构ID
		List<String> institutionIdList = new ArrayList<>();
		institutionIdList.add(institutionId);
		if(dtHealthManageInstitutionGroupList != null && dtHealthManageInstitutionGroupList.size() > 0){
			//存在子ID则全部加入in条件查询
			for(DtHealthManageInstitutionGroupEntity dtHealthManageInstitutionGroup:dtHealthManageInstitutionGroupList){
				institutionIdList.add(dtHealthManageInstitutionGroup.getChildInstitutionId());
			}
		}
		p.setInstitutionIdList(institutionIdList);
        //去除原机构ID条件
        p.setInstitutionId(null);
        //数据查询
      	List<SummarizeResModel> list = summarizeService.searchInstitutions(p);

        if ( list == null  || list.size() < 1){
      		throw new RuntimeException("");
      	}
        //获取初始数据
		SummarizeResModel agoData = list.get(0);
		//数据大于一条则累加
        if(list.size() > 1){
			for(int i=1;i<list.size();i++){
				SummarizeResModel data = list.get(i);
				//数据存在累加数据
				Integer prescriptionIllegalCnt = agoData.getPrescriptionIllegalCnt() + data.getPrescriptionIllegalCnt();
				Integer disinfectIllegalCnt = agoData.getDisinfectIllegalCnt() + data.getDisinfectIllegalCnt();
				Integer disinfectIllegalCntA = agoData.getDisinfectIllegalCntA() + data.getDisinfectIllegalCntA();
				Integer disinfectIllegalCntB = agoData.getDisinfectIllegalCntB() + data.getDisinfectIllegalCntB();
				Integer wasteIllegalCnt = agoData.getWasteIllegalCnt() + data.getWasteIllegalCnt();
				Integer sewageIllegalCnt = agoData.getSewageIllegalCnt() + data.getSewageIllegalCnt();
				Integer sewageIllegalCntA = agoData.getSewageIllegalCntA() + data.getSewageIllegalCntA();
				Integer sewageIllegalCntB = agoData.getSewageIllegalCntB() + data.getSewageIllegalCntB();
				Integer sewageIllegalCntC = agoData.getSewageIllegalCntC() + data.getSewageIllegalCntC();
				Integer remoteIllegalCnt=agoData.getRemoteIllegalCnt()+data.getRemoteIllegalCnt();
				Integer remoteIllegalCntA=agoData.getRemoteIllegalCntA()+data.getRemoteIllegalCntA();
				Integer threeDayIllegalCnt=agoData.getThreeDayIllegalCnt()+data.getThreeDayIllegalCnt();
				Integer threeDayIllegalCntA=agoData.getThreeDayIllegalCntA()+data.getThreeDayIllegalCntA();

				agoData.setPrescriptionIllegalCnt(prescriptionIllegalCnt);
				agoData.setDisinfectIllegalCnt(disinfectIllegalCnt);
				agoData.setDisinfectIllegalCntA(disinfectIllegalCntA);
				agoData.setDisinfectIllegalCntB(disinfectIllegalCntB);
				agoData.setWasteIllegalCnt(wasteIllegalCnt);
				agoData.setSewageIllegalCnt(sewageIllegalCnt);
				agoData.setSewageIllegalCntA(sewageIllegalCntA);
				agoData.setSewageIllegalCntB(sewageIllegalCntB);
				agoData.setSewageIllegalCntC(sewageIllegalCntC);
				agoData.setRemoteIllegalCnt(remoteIllegalCnt);
				agoData.setRemoteIllegalCntA(remoteIllegalCntA);
				agoData.setThreeDayIllegalCnt(threeDayIllegalCnt);
				agoData.setThreeDayIllegalCntA(threeDayIllegalCntA);
				//替换名称为父ID对应名称
				if(data.getInstitutionName() != null){
					agoData.setInstitutionName(data.getInstitutionName());
				}
				//替换机构ID为父ID对应机构ID
				if(data.getInstitutionId() != null){
					agoData.setInstitutionId(data.getInstitutionId());
				}
				//存在一个状态为异常，则替换为异常
				if(data.getPrescriptionCheckSt() != 0){
					agoData.setPrescriptionCheckSt(-1);
				}
				if(data.getDisinfectCheckSt() != 0){
					agoData.setDisinfectCheckSt(-1);
				}
				if(data.getWasteCheckSt() != 0){
					agoData.setWasteCheckSt(-1);
				}
				if(data.getSewageCheckSt() != 0){
					agoData.setSewageCheckSt(-1);
				}
				if (data.getRemoteCheckSt()!=0){
					agoData.setRemoteCheckSt(-1);
				}
				if (data.getThreeDayCheckSt()!=0){
					agoData.setThreeDayCheckSt(-1);
				}
			}
		}
     	// 查询实施
      	ret.put("errcode", 0);

		ret.put("resModel", agoData);
		ret.put("errMsg", "");
		return ret;
	}

	@Inject private MenuService menuService;
	@Inject private SummarizeService summarizeService;
	@Inject private SewageService sewageService;
	@Inject private InvsItemService invsItemService;
	@Inject private ViolationMessageService violationMessageService;
	@Inject private DtHealthManageInstitutionGroupService dtHealthManageInstitutionGroupService;
	@Inject private DataDictionaryService dataDictionaryService;
}
